///<reference path='../typings/weapp.d.ts' />
import tools from './tools'

class Service {

	value: any;
	constructor() {
		this.init()
	}
	public tools;

	init() {
		this.tools = tools
		this.initDefaults()
		this.initMethods()
	}

	initDefaults() {

	}

	public noPromiseMethods = [
		'stopRecord',
		'pauseVoice',
		'stopVoice',
		'pauseBackgroundAudio',
		'stopBackgroundAudio',
		'showNavigationBarLoading',
		'hideNavigationBarLoading',
		'createAnimation',
		'createContext',
		'hideKeyboard',
		'stopPullDownRefresh',
		'switchTab'
	]

	public instanceSource = {
		method: Object.keys(wx)
	}

	initMethods() {
		for (let key in this.instanceSource) {
			this.instanceSource[key].forEach((method, index) => {
				this[method] = (...args) => {
					if (this.noPromiseMethods.indexOf(method) !== -1 || method.substr(0, 2) === 'on' || /\w+Sync$/.test(method)) {
						return wx[method](...args)
					}
					return this.__defaultRequest(method, ...args)
				}
			})
		}

		this.navigateTo = (url: string, params?) => {
			const $$url = this.tools.buildUrl(url, params)
			return new Promise((resolve, reject) => {
				wx.navigateTo({
					'url': $$url,
					'success': res => resolve(res),
					'fail': res => reject(res),
				})
			})
		}

		this.redirectTo = (url: string, params?) => {
			const $$url = this.tools.buildUrl(url, params)
			return new Promise((resolve, reject) => {
				wx.redirectTo({
					'url': $$url,
					'success': res => resolve(res),
					'fail': res => reject(res),
				})
			})
		}

		this.navigateBack = (delta: number = 1) => {
			wx.navigateBack({
				'delta': delta
			})
		}

		this.switchTab = (url: string) => {
			wx.switchTab({
				'url': url
			})
		}

		this.showToast = (title: string, image?: string) => {
			wx.showToast({
				'title': title,
				//'mask': true,
				'image': image,
				//duration:20000
			});
		}

		this.showLoading = (title: string = '加载中') => {
			wx.showLoading({
				'title': title,
				//'mask': true
			})
		}

	}

	public redirectTo = (url: string, params?) => { }
	public navigateTo = (url: string, params?) => { }
	public switchTab = (url: string) => { }
	public navigateBack = (delta: number = 1) => { }

	/**
	 * 显示 loading 提示框, 需主动调用 wx.hideLoading 才能关闭提示框
	 */
	public showLoading = (title: string = '加载中') => { }
	public showToast = (title: string, image?: string) => { }

	__defaultRequest(method = '', obj?: any) {
		obj = obj || {};
		return new Promise((resolve, reject) => {
			obj.success = (res) => resolve(res)
			obj.fail = (res) => reject(res)
			wx[method](obj)
		})
	}
}

export default new Service()